<template>
  <div class="table-box">
    <div v-loading="loading">
      <table>
        <tr>
          <td>模板上传状态:</td>
          <td v-if="linkStatus == true"><p style="padding: 0 8px; color: #00aa00">已上传</p></td>
          <td v-if="linkStatus == false"><p style="padding: 0 8px; color: #ff0000">未上传</p></td>
          <td>
            <el-upload ref="uploadRef" action="" :auto-upload="false" :show-file-list="false" :on-change="uploadChange">
              <template #trigger>
                <el-button type="primary" link plain>上传docx模板 </el-button>
              </template>
              <!-- <template #tip>
			      <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
			    </template> -->
            </el-upload>
            <!-- <el-button type="primary" link @click="checkAndSave">上传模板</el-button> -->
          </td>
          <td>
            <el-button type="primary" link @click="checkAndSave">下载模板</el-button>
          </td>
        </tr>
      </table>
    </div>
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
      row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="addCustomerReportTemplate">新增</el-button>
        <el-button type="primary" plain @click="EditGroup(scope.selectedList)">编辑</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="deleteGroup(scope.selectedList)">
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      表格操作
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="EditGroup([scope.row])">编辑</el-button>
        <el-button type="primary" link :icon="EditPen" @click="deleteGroup([scope.row])">删除</el-button>
      </template>
    </ProTable>
    <ImportExcel ref="dialogRef" />
    <el-dialog title="自定义图片" v-model="dialogTableVisible">
      <div :style="{ height: '300px' }">
        <el-form style="width: 100%" label-width="160px" ref="ruleFormRef" :rules="rules" :model="addForm">
          <el-form-item label="报表输出图片键名 :" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="图片标题 :" prop="title">
            <el-input v-model="addForm.title" />
          </el-form-item>
          <el-form-item label="分类字段 :" prop="requestCategoryStr">
            <el-input v-model="addForm.requestCategoryStr" />
          </el-form-item>
          <el-form-item label="绑定岗位的子标题 :" prop="reportPictureShowName">
            <el-input v-model="addForm.reportPictureShowName" />
          </el-form-item>
          <el-button type="primary" @click="onSubmit(ruleFormRef)"> 确认 </el-button>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { User, RoleManager, dataDictionary } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
// import ImportExcel from "@/views/accessControl/roleManagement/components/ImportExcel/index.vue";
import UserDrawer from "@/views/dataDictionary/groupManagement/components/groupDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import TreeFilter2 from "@/views/accessControl/roleManagement/components/authSetting/openSetting.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Avatar } from "@element-plus/icons-vue";
// import ImportExcel from "@/views/systemTools/customerReportTemplate/ImportExcel/index.vue";
import {
  getUserList,
  deleteUser,
  editUser,
  addUser,
  changeUserStatus,
  resetUserPassWord,
  exportUserInfo,
  BatchAddUser
} from "@/api/modules/user";
import { getPpbxToken } from "@/api/modules/index";
import { findNoticeRulePager, delNoticeRules } from "@/api/modules/systemTools";
import { roleFind, deleteRole, tempRole, importRoleData, exportRole, setResourceByRoleIds } from "@/api/modules/accessController";
import { dataDictionaryGroupFind, exportDataDictionaryGroup } from "@/api/modules/dataDictionary";
import {
  findCallLogPage,
  updateFollowStatusByIds,
  saveAndCheck,
  getPpbxIpAndPortUsernamePassword
} from "@/api/modules/callAgent";
import {
  findReportPicturePage,
  saveReportPicture,
  updateReportPicture,
  deleteReportPicture,
  findTemplateUrl,
  saveTemplateUrl
} from "@/api/modules/reportPicture";
import { uploadAttr } from "@/api/modules/common";
import type { UploadProps } from "element-plus";

import WebSocket from "@/api/modules/websocket";
import { useUserStore } from "@/stores/modules/user";
const route = useRoute();
const router = useRouter();

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});
const loading = ref(false);
const templateUrl = ref("");

const ruleFormRef = ref<FormInstance>();
const addForm = reactive({
  id: "",
  name: "",
  requestCategoryStr: "",
  title: "",
  reportPictureShowName: ""
});

const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入报表输出图片键名", trigger: "blur" }],
  requestCategoryStr: [{ required: true, message: "请输入", trigger: "blur" }],
  title: [{ required: true, message: "请输入图片名称", trigger: "blur" }],
  reportPictureShowName: [{ required: false, message: "请输入绑定岗位的子标题", trigger: "blur" }]
});

const dialogTableVisible = ref(false);
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // request problem change configureItem knowledge
      // tabStore.removeTabs(route.fullPath);
      // let tmp = {
      //   type: addForm.module,
      //   formCustomName: addForm.name
      // };
      saveReportPicture(addForm, "reportPictureQueryDTO", []).then(res => {
        if (res != null && res.toString() != "") {
          ElMessage.error(res.toString());
        } else {
          ElMessage.success("操作成功");
          dialogTableVisible.value = false;
          proTable.value?.clearSelection();
          proTable.value?.getTableList();
        }
      });
    } else {
      ElMessage.error("请正确填写表单");
    }
  });
};

// 上传附件
const uploadChange: UploadProps["onChange"] = (uploadFile: any) => {
  // const isExcel = uploadFile.fileType!.includes(file.type as File.ExcelMimeType);
  // // const fileSize = file.size / 1024 / 1024 < parameter.value.fileSize!;
  // if (!isExcel)
  //   ElNotification({
  //     title: "温馨提示",
  //     message: "上传文件只能是 csv 格式！",
  //     type: "warning"
  //   });
  //   return
  loading.value = true;
  let params = new FormData();
  params.append("filedata", uploadFile.raw);
  uploadAttr("yuehaishuiwu_zhengshi", params)
    .then((res: any) => {
      saveTemplateUrl(res.msg)
        .then(() => {
          findTemplateUrl().then(res => {
            if (res != null && res.toString() != "") {
              templateUrl.value = res.toString();
              linkStatus.value = true;
            } else {
              linkStatus.value = false;
            }
          });
          loading.value = false;
        })
        .catch(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      loading.value = false;
    });
};

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行

const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
const form = ref({
  ipAndPort: "",
  username: "",
  password: ""
});
const linkStatus = ref(true);
const checkAndSave = (data: any) => {
  const a = document.createElement("a");
  a.href = import.meta.env.VITE_API_URL + "/itsm-webapp/pages/attachment!downloadImgNewPage.action?filePath=" + templateUrl.value;
  a.target = "_blank";
  a.click();
  a.remove();
};

const showIpandPort = ref(false);
onMounted(() => {
  findTemplateUrl().then(res => {
    if (res != null && res.toString() != "") {
      templateUrl.value = res.toString();
      linkStatus.value = true;
    } else {
      linkStatus.value = false;
    }
  });
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  delete newParams.pageNum;
  delete newParams.pageSize;
  return findReportPicturePage(newParams, "reportPictureQueryDTO", ["_search", "page", "rows"]);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};
export interface resList {
  callTime: string;
  companyNo: string;
  createTime: string;
  creator: string;
  custName: string;
  dataFlag: string;
  description: string;
  followName: string;
  id: string;
  indexContent: string;
  isFollow: number;
  lastUpdateTime: string;
  lastUpdater: string;
  operId: string;
  optimisticLock: string;
  phone: string;
  remark: string;
  ringTime: string;
  status: number;
  uid: string;
  name: string;
  requestCategoryStr: string;
  title: string;
  reportPictureShowName: string;
}
// 表格配置项
const columns = reactive<ColumnProps<resList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "name", label: "报表输出图片键名", search: { el: "input" }, sortable: true, width: 200 },
  { prop: "title", label: "图片标题", search: { el: "input" }, sortable: true, width: 200 },
  { prop: "requestCategoryStr", label: "分类字段" },
  { prop: "reportPictureShowName", label: "绑定岗位的子标题" },
  { prop: "operation", label: "操作项", fixed: "right", width: 160 }
]);
const addCustomerReportTemplate = () => {
  dialogTableVisible.value = true;
  addForm.name = "";
  addForm.requestCategoryStr = "";
  addForm.id = "";
  addForm.title = "";
  addForm.reportPictureShowName = "";
};
// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 删除
const deleteAccount = async (params: resList) => {
  deleteGroup([params]);
  proTable.value?.getTableList();
};

const deleteGroup = async (id: any[]) => {
  if (id.length == 0) {
    ElMessage.error("至少选择一条数据");
    return;
  }
  console.log(id[0].name);
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?ids=" + id[i].id;
    } else {
      idsStr = idsStr + "&ids=" + id[i].id;
    }
    NameStr = NameStr + id[i].name + ",";
  }
  ElMessageBox.confirm("是否删除选中的数据：" + NameStr + " ？", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      //await useHandleData(deleteUser, { id }, "删除所选用户信息");
      deleteReportPicture(idsStr).then(res => {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};
const EditGroup = async (id: any[]) => {
  if (id.length == 0) {
    ElMessage.error("至少选择一条数据");
    return;
  }
  if (id.length > 1) {
    ElMessage.error("只能选一条数据编辑");
    return;
  }
  dialogTableVisible.value = true;
  addForm.name = id[0].name;
  addForm.requestCategoryStr = id[0].requestCategoryStr;
  addForm.id = id[0].id;
  addForm.title = id[0].title;
  addForm.reportPictureShowName = id[0].reportPictureShowName;
};
</script>
